package com.restaurant.application.indexes.consumptionlist;

import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.nebutown.base.ViewSpec;
import com.nebutown.base.data.View;
import com.nebutown.base.data.ViewUpdate;
import com.nebutown.commonunits.dataface.DataModes;
import com.nebutown.commonunits.dataface.EntryTypes;
import com.nebutown.commonunits.dataface.FormShell;
import com.nebutown.commonunits.dataface.TableShell;
import com.nebutown.commonunits.dataface.definitions.*;
import com.nebutown.commonunits.uidataface.UIDataFace;
import com.nebutown.commonunits.utils.DateTimeUtils;
import com.nebutown.generation.basictype.UID;
import com.restaurant.application.accumulate.Accumulate;
import com.restaurant.application.consumption.Consumption;
import com.restaurant.application.consumption.support.ConsumptionData;
import com.restaurant.application.consumption.support.OrderData;
import com.restaurant.application.indexes.accumulatelist.mysql.AccumulateListTableBean;
import com.restaurant.application.indexes.accumulatelist.mysql.AccumulateListTableCriteria;
import com.restaurant.application.indexes.accumulatelist.mysql.AccumulateListTableImpl;
import com.restaurant.application.indexes.consumptionlist.mysql.ConsumptionListBean;
import com.restaurant.application.indexes.consumptionlist.mysql.ConsumptionListCriteria;
import com.restaurant.application.indexes.consumptionlist.mysql.ConsumptionListImpl;
import com.restaurant.application.indexes.consumptionlist.support.AbstractAssistConsumptionList;
import com.restaurant.application.indexes.consumptionlist.support.BandBean;
import com.restaurant.application.indexes.customerlist.mysql.CustomerListBean;
import com.restaurant.application.indexes.customerlist.mysql.CustomerListCriteria;
import com.restaurant.application.indexes.customerlist.mysql.CustomerListImpl;
import com.restaurant.application.minifacade.data.ConsumptionBO;
import com.restaurant.application.minifacade.data.ConsumptionListBO;
import com.restaurant.application.service.feigh.Gateway2dfires;
import com.restaurant.application.service.feigh.IGateway2dfire;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

public class AssistConsumptionListImpl extends AbstractAssistConsumptionList {
    static final String ENTITY_ID = "00449276";
    @Override
    public ViewUpdate viewConsumption(int[] seq) {
        List<ConsumptionListBean> search = getIndex(ConsumptionListImpl.class).search(new ConsumptionListCriteria().withRecordId((long) seq[0]), null, 1);
        return returnView(getUnit(search.get(0).getConsumptionUid()).getFullView());
    }

    @Override
    public ViewUpdate doSearchPath(ConsumptionListCriteria criteria, int[] seq) {
        return returnView(newCommonTable(criteria, 1));
    }

    @Override
    public View getFullView() {
        return newCommonTable(new ConsumptionListCriteria(), 1);
    }

    @Override
    public View getViewLead(ViewSpec viewSpec) {
        return null;
    }

    @Override
    // todo 门店id
    public List<OrderData> getOrderList(OrderData data) {
        IGateway2dfire.TResponse str = Gateway2dfires.getOrderList(ENTITY_ID, null, null, null);
        List<IGateway2dfire.ShopOrderVo> data1 = str.getData().getData();
        List<OrderData> collect = Lists.newArrayList();
        if (Objects.nonNull(data1)) {
            collect = data1.stream().filter(e -> {
                return (Objects.equals(data.getPosition(), e.getOrderVo().getSeatCode()) || Strings.isNullOrEmpty(data.getPosition())) && !Objects.equals(e.getOrderVo().getStatus(), 3);
            }).map(order -> {
                return new OrderData().withTime(order.getOrderVo().getOpenTime()).withNumber(order.getOrderVo().getCode().toString())
                        .withPosition(order.getOrderVo().getSeatCode()).withTotalPrice(order.getServiceBillVo().getOriginTotal())
                        .withFactPrice(order.getTotalPayVo().getReceiveAmount());
            }).collect(Collectors.toList());
        }
        return collect;
    }

    @Override
    public String bandToCustomer(BandBean data) {
        List<CustomerListBean> search = getIndex(CustomerListImpl.class).search(new CustomerListCriteria().withNumberEquals(data.getCustomerId()).withPhoneEquals(data.getPhone()), null, 1);
        // 用户增加消费记录，并绑定积分
        if (search.size() > 0) {
            ConsumptionData init = new ConsumptionData().withOrderId(data.getNumber()).withCustomer(search.get(0).getCustomerUid())
                    .withTotalPrice(data.getFinalPrice());
            if (Objects.nonNull(data.getEnsurePrice())) {
                init.withFinalPrice(data.getEnsurePrice());
            } else {
                init.withFinalPrice(data.getFinalPrice());
            }
            createNode(Consumption.class).init(init);
        }
        return "success";
    }

    @Override
    public Double getTotal(UID uid) {
        List<ConsumptionListBean> search = getIndex(ConsumptionListImpl.class)
                .search(new ConsumptionListCriteria().withCustomerUidEquals(uid), null, 10000);
        if (search.size() > 0) {
            return search.stream().mapToDouble(ConsumptionListBean::getFinalPrice).sum();
        }
        return 0.00;
    }

    @Override
    public ConsumptionListBO getHistory() {
        UID gate = getGate();
        List<AccumulateListTableBean> search = getIndex(AccumulateListTableImpl.class).search(new AccumulateListTableCriteria().withCustomerUIDEquals(gate), null, 10000);
        if (search.size() > 0) {
            List<ConsumptionBO> collect = search.stream().map(e -> {
                if (Objects.equals(e.getType(), Accumulate.ACCUMULATE_INCREASE_CONSUMER)) {
                    Double finalPrice = getUnit(Consumption.class, UID.recover(e.getDetail())).getConsumeData().getFinalPrice();
                    return new ConsumptionBO().withContent(Accumulate.ACCUMULATE_INCREASE_CONSUMER).withIntegral(e.getPoints())
                            .withMoney(finalPrice).withPayTime(e.getCreateTime());
                } else if (Objects.equals(e.getType(), Accumulate.ACCUMULATE_DECREACE_EXCHANGE)) {
                    return new ConsumptionBO().withContent(Accumulate.ACCUMULATE_DECREACE_EXCHANGE).withIntegral(-e.getPoints())
                            .withPayTime(e.getCreateTime());
                } else {
                    return new ConsumptionBO().withContent(Accumulate.ACCUMULATE_INCREASE_SIGNIN).withIntegral(e.getPoints())
                            .withPayTime(e.getCreateTime());
                }
            }).collect(Collectors.toList());
            return new ConsumptionListBO().withLists(collect);
        }
        return new ConsumptionListBO();
    }

    private View newCommonTable(ConsumptionListCriteria criteria, int pageNum) {
        int pageSize = 10;
        int start = (pageNum - 1) * pageSize;
        int stop = pageNum * pageSize;
        int totalRecord = getIndex(ConsumptionListImpl.class).count(criteria);
        int totalPage = (totalRecord + pageSize - 1) / pageSize;
        List<ConsumptionListBean> consumptionList = getIndex(ConsumptionListImpl.class).search(criteria, null, start, stop);
        PageInfo pageInfo = new PageInfo()
                .withPageNum(pageNum)
                .withPageSize(pageSize)
                .withTotalPage(totalPage)
                .withTotalRecord(totalRecord);
        PageForm pageForm = newFormShell(criteria, consumptionList, pageInfo).getForm();
        return getSingleton(UIDataFace.class).newGenericForm(unitPosition(), pageForm);
    }


    private FormShell newFormShell(ConsumptionListCriteria criteria, List<ConsumptionListBean> consumptionList, PageInfo pageInfo) {

        FormShell formShell = new FormShell("客户消费", 3, 2);

        formShell.source(criteria, DataModes.EDIT);

        formShell.at(0, 0, "客户名称")
                .getEntry(ConsumptionListCriteria.FN_CUSTOMERNAMELIKE, criteria.getCustomerNameLike())
                .placeHolder("客户名")
                .simpleEntry(EntryTypes.STRING)
                .getContent().setEditable(true);

        formShell.at(0, 1, "消费门店")
                .getEntry(ConsumptionListCriteria.FN_SHOPNAMELIKE, criteria.getShopNameLike())
                .simpleEntry(EntryTypes.STRING)
                .getContent().setEditable(true);

        formShell.at(0, 1, "搜索")
                .buttonField(getPath(CMD_DOSEARCHPATH), "", true);


        TableShell<ConsumptionListBean> tableShell = new TableShell(ConsumptionListBean.class, consumptionList).withPageInfo(pageInfo);

        tableShell.createColumn(ConsumptionListBean.FN_CUSTOMERNAME).withName("会员名").cellCalculator(b -> {
            ConsumptionListBean bean = (ConsumptionListBean) b;
            return new CellData()
                    .withField(new FieldContent().withSimpleField(bean.getCustomerName()));
        });

        tableShell.createColumn(ConsumptionListBean.FN_WECHATID).withName("微信Id").cellCalculator(b -> {
            ConsumptionListBean bean = (ConsumptionListBean) b;
            return new CellData()
                    .withField(new FieldContent().withSimpleField(bean.getWeChatId()));
        });

        tableShell.createColumn(ConsumptionListBean.FN_RECORDID).withName("支付时间").cellCalculator(b -> {
            ConsumptionListBean bean = (ConsumptionListBean) b;
            return new CellData()
                    .withField(new FieldContent().withSimpleField(DateTimeUtils.toTime(bean.getTime())));
        });

        tableShell.createColumn(ConsumptionListBean.FN_SHOPNAME).withName("门店名称").cellCalculator(b -> {
            ConsumptionListBean bean = (ConsumptionListBean) b;
            return new CellData()
                    .withField(new FieldContent().withSimpleField(bean.getShopName()));
        });

        tableShell.createColumn(ConsumptionListBean.FN_ACCUMULATEPOINTS).withName("获得积分").cellCalculator(b -> {
            ConsumptionListBean bean = (ConsumptionListBean) b;
            return new CellData()
                    .withField(new FieldContent().withSimpleField(bean.getAccumulatePoints().toString()));
        });

        tableShell.createColumn(ConsumptionListBean.FN_FINALPRICE).withName("消费金额").cellCalculator(b -> {
            ConsumptionListBean bean = (ConsumptionListBean) b;
            return new CellData()
                    .withField(new FieldContent().withSimpleField(bean.getFinalPrice().toString()));
        });

        tableShell.createColumn("删除").withName("删除").cellCalculator(b -> {
            ConsumptionListBean bean = (ConsumptionListBean) b;
            return new CellData()
                    .withField(new FieldContent().withButton(new ButtonField().withLabel("删除").withButtonPath(getPath(CMD_VIEWCONSUMPTION, bean.getRecordId()))));
        });

        formShell.at(2, 0, "会员签到列表")
                .large(3, 1)
                .getEntry("error", "")
                .tableEntry(tableShell);

        return formShell;
    }
}
